/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: DepthViewPresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.kline.presenter;

import android.text.TextUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import io.bhex.app.base.AppUI;
import io.bhex.sdk.quote.bean.DepthDataBean;
import io.bhex.app.utils.copy.DeepCopy;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BaseFragmentPresenter;

/**
 * ================================================
 * 描   述：深度图
 * ================================================
 */

public class DepthViewPresenter extends BaseFragmentPresenter<DepthViewPresenter.DepthViewUI> {

    private DepthDataBean data;

    public interface DepthViewUI extends AppUI {


        void showDepthView(DepthDataBean data);

        void getDepthDataFailed(String msg);

        void showDepthView(Map<String, String> mapA, Map<String, String> mapB);
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, DepthViewUI ui) {
        super.onUIReady(activity, ui);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 深度数据
     *
     * @param depthDataBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DepthDataBean depthDataBean) {
        if (depthDataBean == null)
            return;
        DepthDataBean data = (DepthDataBean) DeepCopy.copy(depthDataBean);
        //排序
        List<List<String>> a;
        List<List<String>> b;
        if (data.getA() != null) {
            a = data.getA();
        }else{
            a = new ArrayList<>();
        }

        if (data.getB() != null) {
            b = data.getB();
        }else{
            b = new ArrayList<>();
        }

        data = sortData(data, depthDataBean.f);
        data = mergeData(data);
        getUI().showDepthView(data);
    }

    /**
     * 合并数据 删除价格多的数据
     * @param data
     * @return
     */
    private DepthDataBean mergeData(DepthDataBean data) {
        List<List<String>> a = data.getA();
        List<List<String>> b = data.getB();
        String aMax="0";
        String aMin="0";
        if (a != null&&a.size()>0) {
            if (a.size()>100) {
                a = a.subList(0,100);
                data.setA(a);
            }
            aMax = a.get(a.size() - 1).get(0);
            aMin = a.get(0).get(0);
        }
        float aMinF = new BigDecimal(aMin).floatValue();
        float dValueOfA = new BigDecimal(aMax).subtract(new BigDecimal(aMin)).floatValue();
        String bMax="0";
        String bMin ="0";
        if (b != null&&b.size()>0) {
            int bSize = b.size();
            if (bSize>100) {
                b = b.subList(bSize-100,bSize);
                data.setB(b);
            }
            bMax = b.get(b.size() - 1).get(0);
            bMin = b.get(0).get(0);
        }
        float bMaxF = new BigDecimal(bMax).floatValue();
        float dValueOfB = new BigDecimal(bMax).subtract(new BigDecimal(bMin)).floatValue();
        if (dValueOfA>dValueOfB && b.size()>1){
            //A 多
            for (int i = a.size() - 1; i >= 0; i--) {
                String priceStr = a.get(i).get(0);
                float price = new BigDecimal(priceStr).floatValue();
                if (price>aMinF+dValueOfB){
                    a.remove(i);
                }
            }

            //判断是否需要补一根数据
            String priceStr = a.get(a.size()-1).get(0);
            float price = new BigDecimal(priceStr).floatValue();
            if (price!=aMinF+dValueOfB){
                List<String> aLast = new ArrayList<>();
                aLast.add(String.valueOf(aMinF+dValueOfB));
                aLast.add("0");
                a.add(aLast);
            }



        }else if(dValueOfA<dValueOfB && a.size()>1){
            //B 多
            for (int i = b.size() - 1; i >= 0; i--) {
                String priceStr = b.get(i).get(0);
                float price = new BigDecimal(priceStr).floatValue();
                if (price<bMaxF-dValueOfA){
                    b.remove(i);
                }
            }

            //判断是否需要补一根数据
            String priceStr = b.get(0).get(0);
            float price = new BigDecimal(priceStr).floatValue();
            if (price!=aMinF+dValueOfB){
                List<String> bLast = new ArrayList<>();
                bLast.add(String.valueOf(bMaxF-dValueOfA));
                bLast.add("0");
                b.add(0,bLast);
            }

        }
        return data;

    }


    Map<String, String> mapA = new TreeMap<>();
    Map<String, String> mapB = new TreeMap<>();

    /**
     * 数据排序
     *
     * @param depthDataBean
     * @return
     */
    private DepthDataBean sortData(DepthDataBean depthDataBean, boolean f) {
        if(f == true) {
            mapA.clear();
            mapB.clear();
        }

        List<List<String>> a = depthDataBean.getA();
        for (List<String> result : a) {
            float value = TextUtils.isEmpty(result.get(1)) ? 0 : Float.valueOf(result.get(1));
            if (value > 0) {
                mapA.put(result.get(0), result.get(1));
            } else {
                mapA.remove(result.get(0));
            }
        }

        List<List<String>> b = depthDataBean.getB();
        for (List<String> result : b) {
            float value = TextUtils.isEmpty(result.get(1)) ? 0 : Float.valueOf(result.get(1));
            if (value > 0) {
                mapB.put(result.get(0), result.get(1));
            } else {
                mapB.remove(result.get(0));
            }

        }

        mapA = sortMapByKey(mapA);
        mapB = sortMapByKey(mapB);

        List<List<String>> A = new ArrayList<>();
        for (String key : mapA.keySet()) {
            ArrayList<String> item = new ArrayList<>();
            item.add(key);
            item.add(mapA.get(key));
            A.add(item);
        }
        depthDataBean.setA(A);

        List<List<String>> B = new ArrayList<>();
        for (String key : mapB.keySet()) {
            ArrayList<String> item = new ArrayList<>();
            item.add(key);
            item.add(mapB.get(key));
            B.add(item);
        }
        depthDataBean.setB(B);
        return depthDataBean;
    }

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return new TreeMap<String, String>();
        }

        Map<String, String> sortMap = new TreeMap<String, String>(
                new MapKeyComparator());

        sortMap.putAll(map);

        return sortMap;
    }


    //比较器类
    static class MapKeyComparator implements Comparator<String> {

        @Override
        public int compare(String str1, String str2) {
            //empty处理
            if (TextUtils.isEmpty(str1)) {
                str1 = "0";
            }
            if (TextUtils.isEmpty(str2)) {
                str2 = "0";
            }

            return new BigDecimal(str1).compareTo(new BigDecimal(str2));
        }
    }

}
